//
//  ProductDataListViewController.m
//  rrbi
//
//  Created by MyMac on 2019/5/6.
//

#import "ProductDataListViewController.h"

#import "FinancaialOrderModel.h"
#import "ProductDataListCell.h"

#import "UICustomDatePicker.h"
#import "TimeSectionView.h"

@interface ProductDataListViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,TimeSectionViewDelegate>

@property (nonatomic, strong) UITableView *tabelView;
@property (nonatomic, strong) NSMutableArray *mainArray;
@property (nonatomic, strong) UITextField *searchTextFiled;
@property (nonatomic, copy) NSString *time_ymd;
@property (nonatomic, copy) NSString *begTime_hour;
@property (nonatomic, copy) NSString *endTime_hour;

@property (nonatomic, strong) UIButton *yearTimeButton;
@property (nonatomic, strong) UIButton *hourTimeButton;
@property (nonatomic, strong) TimeSectionView *timeView;


@end


@implementation ProductDataListViewController
- (NSMutableArray *)mainArray {
    if (!_mainArray) {
        _mainArray  = [NSMutableArray array];
    }
    return _mainArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.time_ymd =@"";
    self.begTime_hour = @"";
    self.endTime_hour = @"";
    //  顶部搜索
    UIView *topView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 44)];
    self.navigationItem.titleView = topView;
    if (@available(iOS 11.0, *)) {
        [topView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(240);
            make.height.mas_equalTo(44);
        }];
    }
    
    
    UIView *searchView = [[UIView alloc]initWithFrame:CGRectMake(0, 4.5, 240, 35)];
    searchView.backgroundColor = getColor(@"F3F4F7");
    searchView.layer.cornerRadius = 5;
    searchView.layer.masksToBounds = YES;
    [topView addSubview:searchView];
    [searchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(topView.mas_centerX);
        make.centerY.equalTo(topView.mas_centerY);
        make.width.mas_equalTo(240 / WIDTH_6S_SCALE);
        make.height.mas_equalTo(35 / HEIGHT_6S_SCALE);
    }];
    // 搜索框
    [searchView addSubview:self.searchTextFiled];
    [self.searchTextFiled mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(searchView).offset(5);
        make.centerY.equalTo(searchView.mas_centerY);
        make.right.equalTo(searchView);
        make.height.equalTo(searchView);
    }];
    
    
    
    [self createTAbelView];
    
    [self getShopData];
}

- (void)createTAbelView {
    
    self.tabelView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-SafeAreaTopHeight) style:UITableViewStyleGrouped];
    self.tabelView.delegate = self;
    self.tabelView.dataSource = self;
    [self.view addSubview:self.tabelView];
    self.tabelView.showsVerticalScrollIndicator = NO;
    self.tabelView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tabelView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    
    if (@available(iOS 11.0, *))
    {
        self.tabelView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        self.tabelView.estimatedRowHeight = 0;
        self.tabelView.estimatedSectionFooterHeight = 0;
        self.tabelView.estimatedSectionHeaderHeight = 0;
    }
    
    [self.tabelView registerNib:[UINib nibWithNibName:NSStringFromClass([ProductDataListCell class]) bundle:nil] forCellReuseIdentifier:@"productDataListCell"];
    
    [self createHeadTabelView];
    
    
    self.timeView = [[TimeSectionView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-SafeAreaTopHeight)];
    self.timeView.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0.3];
    self.timeView.delegate = self;
    [self.view addSubview:self.timeView];
    self.timeView.hidden = YES;
}

- (void)createHeadTabelView {
    
    UIView *headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 50)];
    headView.backgroundColor = [UIColor whiteColor];
    
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0.5)];
    lineView.backgroundColor = [UIColor colorWithRed:240.0/255.0 green:240.0/255.0 blue:240/255.0 alpha:1];
    [headView addSubview:lineView];

    self.yearTimeButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 1, SCREEN_WIDTH*0.5-70, 41)];
    [self.yearTimeButton setTitleColor:[UIColor colorWithRed:0.0/255.0 green:199.0/255.0 blue:0.0/255.0 alpha:1] forState:UIControlStateNormal];
    self.yearTimeButton.contentHorizontalAlignment =  UIControlContentHorizontalAlignmentRight;
    self.yearTimeButton.titleLabel.font = [UIFont systemFontOfSize:13];
    NSDate *date =[NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy"];
    NSInteger currentYear=[[formatter stringFromDate:date] integerValue];
    [formatter setDateFormat:@"MM"];
    NSInteger currentMonth=[[formatter stringFromDate:date]integerValue];
    [formatter setDateFormat:@"dd"];
    NSInteger currentDay=[[formatter stringFromDate:date] integerValue];
    self.time_ymd = [NSString stringWithFormat:@"%ld-%ld-%ld",currentYear,currentMonth,currentDay];
    [self.yearTimeButton setTitle:[NSString stringWithFormat:@"%ld-%ld-%ld",currentYear,currentMonth,currentDay] forState:UIControlStateNormal];
    [self.yearTimeButton addTarget:self action:@selector(yearTimeButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [headView addSubview:self.yearTimeButton];
    
    
    
    self.hourTimeButton = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH*0.5, 1, SCREEN_WIDTH*0.5-70, 41)];
    [self.hourTimeButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    self.hourTimeButton.contentHorizontalAlignment =  UIControlContentHorizontalAlignmentRight;
    self.hourTimeButton.titleLabel.font = [UIFont systemFontOfSize:13];
    [self.hourTimeButton setTitle:[NSString stringWithFormat:@"时间段"] forState:UIControlStateNormal];
    [self.hourTimeButton addTarget:self action:@selector(hourTimeButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [headView addSubview:self.hourTimeButton];
    
    
    UIImageView *imageView1 = [[UIImageView alloc]initWithFrame:CGRectMake(self.yearTimeButton.bounds.size.width, 1, 10, 41)];
    imageView1.image = [UIImage imageNamed:@"下拉"];
    imageView1.tag = 100;
    imageView1.contentMode = UIViewContentModeCenter;
    [headView addSubview:imageView1];
    UIImageView *imageView2 = [[UIImageView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH*0.5-70+SCREEN_WIDTH*0.5, 1, 10, 41)];
    imageView2.image = [UIImage imageNamed:@"下拉拷贝2"];
    imageView2.tag = 200;
    imageView2.contentMode = UIViewContentModeCenter;
    [headView addSubview:imageView2];
    
    
    
    UIView *lineView1 = [[UIView alloc]initWithFrame:CGRectMake(0, 42, SCREEN_WIDTH, 8)];
    lineView1.backgroundColor = [UIColor colorWithRed:240.0/255.0 green:240.0/255.0 blue:240/255.0 alpha:1];
    [headView addSubview:lineView1];
    self.tabelView.tableHeaderView = headView;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.mainArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 260;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return nil;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return nil;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.00001;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.00001;;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ProductDataListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"productDataListCell"];
    
    FinancaialOrderModel *model = self.mainArray[indexPath.row];
    [cell updataDataWithModel:model];
    
    cell.FinancaialOrderBlock = ^{
        NSLog(@"%@",model);
    };
    return cell;
}


#pragma mark - 数据请求
- (void)getShopData{
    
    AFHTTPSessionManager *mgr=[AFHTTPSessionManager manager];
    NSDictionary* arg = @{
                          @"ru_id":[UserModel sharedInstanced].ru_Id,
                          @"ince":@"goods_data_list",
                          @"search_key":self.searchTextFiled.text,
                          @"time_ymd":self.time_ymd,
                          @"time_hour_start":self.begTime_hour,
                          @"time_hour_end":self.endTime_hour
                          };
    
    NSString *URL = [NSString stringWithFormat:@"%@%@",BaseUrl,@"goods_data_list"];
    [mgr POST:URL parameters:arg progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        [WMHelper outPutJsonString:responseObject];
        
        NSInteger flag = [[responseObject objectForKey:@"ret"]integerValue];
        if(flag == 200){
            [self.mainArray removeAllObjects];
            self.mainArray = [FinancaialOrderModel mj_objectArrayWithKeyValuesArray:[responseObject objectForKey:@"list"]];
            
            [self.tabelView reloadData];
            
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error)  {
        [self hidHUD:@"网络异常"];
    }];
    
}

#pragma mark -UITextFieldDelegate
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];//关闭键盘
    
    [self getShopData];
    
    
    return YES;
}

- (void)yearTimeButtonAction {
    __weak typeof(self) weakSelf = self;
    
    [UICustomDatePicker showCustomDatePickerAtView:self.view choosedDateBlock:^(NSDate *date) {
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
        NSString *strDate = [dateFormatter stringFromDate:date];
        weakSelf.time_ymd = strDate;
        [weakSelf.yearTimeButton setTitle:strDate forState:UIControlStateNormal];
        [weakSelf.yearTimeButton setTitleColor:[UIColor colorWithRed:0.0/255.0 green:199.0/255.0 blue:0.0/255.0 alpha:1] forState:UIControlStateNormal];
        UIImageView *image= [weakSelf.view viewWithTag:100];
        image.image =[UIImage imageNamed:@"下拉"];//绿色图片
        
        [self getShopData];
    } cancelBlock:^{
        
    }];
}

- (void)hourTimeButtonAction {

    self.timeView.hidden = NO;
}


- (void)pickerStaTime:(NSString *)staTime endTime:(NSString *)endTime {
   
    self.begTime_hour = staTime;
    self.endTime_hour = endTime;
    UIImageView *image2= [self.view viewWithTag:200];
    image2.image =[UIImage imageNamed:@"下拉"];//绿色图片
    [self.hourTimeButton setTitle:staTime forState:UIControlStateNormal];
    [self.hourTimeButton setTitleColor:[UIColor colorWithRed:0.0/255.0 green:199.0/255.0 blue:0.0/255.0 alpha:1] forState:UIControlStateNormal];
    [self getShopData];
}


#pragma mark - init
- (UITextField *)searchTextFiled
{
    if (!_searchTextFiled) {
        _searchTextFiled = [[UITextField alloc]init];
        _searchTextFiled.backgroundColor = [UIColor clearColor];
        //        _searchTextFiled.backgroundColor = getColor(@"F3F4F7");
        _searchTextFiled.font = [UIFont systemFontOfSize:14];
        _searchTextFiled.textColor = getColor(textColor);
        _searchTextFiled.textAlignment = NSTextAlignmentLeft;
        _searchTextFiled.placeholder = @"搜索商品名、商品编号、商品订单号";
        _searchTextFiled.delegate = self;
        _searchTextFiled.leftViewMode = UITextFieldViewModeAlways;
        _searchTextFiled.leftView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"icon_search_small.png"]];
        _searchTextFiled.keyboardType = UIKeyboardTypeWebSearch;
    }
    return _searchTextFiled;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
